const Router = require('@koa/router')
const ins = require('./instagram.cjs')
const {createDriver, getDriver} = require('./driver.cjs')
const {success, fail, checkParams} = require('./commonApi.cjs')

const env = 'dev'

// 创建一个路由
const makeRoute = () => {
    const router = new Router()
    // 创建一个浏览器实例
    router.post('/createDriver', async (ctx, next) => {
        let {data: {id}} = ctx.request.body
        let driver = await createDriver(id)
        success(ctx)
    })
    router.post('/loginInstagram', async (ctx, next) => {
        let {data: {id}} = ctx.request.body
        let driver = getDriver(id)
        if (driver) {
            ins.initCookies(driver, "https://www.instagram.com/", './cookies')
            success(ctx)
        }
        else {
            fail(ctx, 'driver不存在')
        }
    })

    router.post('/saveInstagramCookies', async (ctx, next) => {
        let {data: {id, path}} = ctx.request.body
        let driver = getDriver(id)
        if (driver) {
            ins.saveCookies(driver, path)
            success(ctx)
        }
        else {
            fail(ctx, 'driver不存在')
        }
    });
    return router
}

function init(app) {
    const router = makeRoute()

    app.use(checkParams)
    app.use(router.routes()).use(router.allowedMethods());
}

module.exports = {init}
